2
2
.
.
1
1
1
1
.
.
3
3
F
F
r
r
o
o
m
m
R
R
e
e
q
q
u
u
e
e
s
s
t
t
P
P
a
a
r
r
a
a
m
m
e
e
t
t
e
e
r
r
s
s
-
-
U
U
s
s
i
i
n
n
g
g
M
M
a
a
p
p
I
I
n
n
f
f
o
o
[
[
G
G
]
]
This tutorial shows how to
Deserialize HTTP Request Parameters into Map<String, Object> (how to automatically load them into Map)
an then use ObjectMapper to load that Map into PersonDTO
This allows us to use @JsonProperty() Annotation to map HTTP Request Parameters to DTO Properties.
This is not possible when directly loading HTTP Request Parameters into DTO (as shown in From Request Parameters -
Using Setters) but the downside is the additional line in the Controller to call new ObjectMapper().convertValue().
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: Controller Annotations, Tomcat Server
PersonDTO
http://localhost:8080/AddPerson
Tomcat
Browser
MyController
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_deserialize_requestparameters_objectmapper (add Spring Boot Starters from the table)
Create Package: DTO (inside main package)
Create Class: PersonDTO.java (inside package DTO)
Create Package: controllers (inside main package)
Create Class: MyController.java (inside package controllers)
PersonDTO.java
package com.ivoronline.springboot_deserialize_requestparameters_objectmapper.DTO;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true) //To avoid Error if Request contains additional Parameters
public class PersonDTO {
@JsonProperty("firstName") //If Request Parameter and DTO Property have different names
public String name;
public String height;
}
MyController.java
package com.ivoronline.springboot_deserialize_requestparameters_objectmapper.controllers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ivoronline.springboot_deserialize_requestparameters_objectmapper.DTO.PersonDTO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/AddPerson")
public String addPerson(@RequestParam Map<String, Object> requestParameters) {
PersonDTO personDTO = new ObjectMapper().convertValue(requestParameters, PersonDTO.class);
return personDTO.name + " is " + personDTO.height + " meters high";
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
http://localhost:8080/AddPerson?firstName=John&height=1.67&age=10
Application Structure
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>